<template>
  <el-card class="box-card">
    <div slot="header" class="header">
      <div class="title">{{ tableName }}</div>
      <el-button type="primary" size="mini" @click="search">搜索</el-button>
      <el-button type="warning" size="mini" @click="truncate">清空</el-button>
      <el-button type="danger" size="mini" @click="drop">删除</el-button>
      <el-button size="mini" @click="reset">重置</el-button>
    </div>
    <div class="body">
      <el-table v-loading="loading" :data="data" border>
        <el-table-column
          v-for="col in columns"
          align="center"
          :key="col.prop"
          v-bind="col"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <template v-if="isImageUrl(scope.row[col.prop])">
              <el-image :src="scope.row[col.prop]" style="height: 120px"/>
            </template>
            <template v-else-if="isLinkUrl(scope.row[col.prop])">
              <el-link type="primary" :href="scope.row[col.prop]">{{
                scope.row[col.prop]
              }}</el-link>
            </template>
            <template v-else>
              <span>{{ scope.row[col.prop] }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="remove(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
          :current-page="pageNo"
          :page="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <edit
      v-if="modal"
      :visible="modal"
      :title="title"
      :data="row"
      :columns="columns"
      @destory="destory"
      @handleSubmit="submit"
    />
  </el-card>
</template>

<script>
import { head, cloneDeep } from "lodash";
import { isImageUrl, isLinkUrl } from "@/utils";
import {
  showColumns,
  pageHandler,
  truncateTable,
  showPrimaryKey,
  deleteHandler,
  updateHandler,
  dropTable,
} from "@/api/knex";
import Edit from "./edit";
export default {
  name: "Table",
  components: {
    Edit,
  },
  data() {
    return {
      title: "",
      total: 0,
      pageNo: 1,
      pageSize: 10,
      data: [],
      row: {},
      columns: [],
      where: {},
      primaryKey: "",
      modal: false,
      loading: false,
    };
  },
  computed: {
    tableName() {
      const path = this.$route.path;
      return head(path.substring(1).split("/"));
    },
  },
  created() {
    this.showPrimaryKey();
    this.initPageRequest();
  },
  methods: {
    isImageUrl,
    isLinkUrl,
    reset() {
      this.initPageRequest();
    },
    async showPrimaryKey() {
      const key = await showPrimaryKey();
      this.primaryKey = key;
    },
    edit(row) {
      this.title = "编辑";
      this.row = cloneDeep(row);
      this.modal = true;
    },
    search() {
      this.title = "查询";
      this.modal = true;
    },
    destory() {
      this.modal = false;
      this.row = {};
    },
    submit(data) {
      if (this.title === "查询") {
        this.handleSearch(data);
      } else {
        this.handleEdit(data);
      }
    },
    handleSearch(data) {
      const where = {};
      this.columns.forEach((k) => {
        where[k.prop] = data[k.prop];
      });
      this.where = where;
      this.initPageRequest();
    },
    handleEdit(data) {
      const where = {};
      where[this.primaryKey] = data[this.primaryKey];
      updateHandler(this.tableName, where, data).then(() => {
        this.initPageRequest();
        this.$message({
          type: "success",
          message: "成功编辑",
        });
      });
    },
    remove(row) {
      this.$alert("确定要删除这条记录?", "消息", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action === "confirm") {
            const where = {};
            where[this.primaryKey] = row[this.primaryKey];
            deleteHandler(this.tableName, where).then(() => {
              this.$message({
                type: "success",
                message: "成功删除",
              });
              this.initPageRequest();
            });
          }
        },
      });
    },
    truncate() {
      this.$alert("确定清空" + this.tableName + "表?", "消息", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action === "confirm") {
            truncateTable(this.tableName).then(() => {
              this.$message({
                type: "success",
                message: "成功清空" + this.tableName + "表",
              });
              this.initPageRequest();
            });
          }
        },
      });
    },
    drop() {
      this.$alert("确定删除" + this.tableName + "表?", "消息", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action === "confirm") {
            dropTable(this.tableName).then(() => {
              this.$message({
                type: "success",
                message: "成功删除" + this.tableName + "表",
              });
              this.$router.push({ path: "/" });
            });
          }
        },
      });
    },
    async initPageRequest() {
      this.loading = true;
      const columns = await showColumns(this.tableName);
      this.columns = columns.map((k) => {
        return {
          prop: k,
          label: k.toUpperCase(),
        };
      });
      const pager = await pageHandler(this.tableName, {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        where: this.where,
      });
      this.total = pager.total;
      this.data = pager.data;
      this.where = {};
      this.loading = false;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.initPageRequest();
    },
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.initPageRequest();
    },
    formItemTypeChanged(prop, value) {
      this.columns[prop] = value;
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  text-transform: uppercase;
}

.header {
  div {
    flex: 1;
  }

  display: flex;
  align-items: center;
}

.pager {
  display: flex;
  align-items: center;
  padding-top: 16px;
  justify-content: flex-end;
}
</style>
